package com.youaishujuhui.devops.web.controller.log;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.youaishujuhui.devops.web.domain.host.Host;
import com.youaishujuhui.devops.web.po.LogResultPO;
import com.youaishujuhui.devops.web.po.SSHExecResult;
import com.youaishujuhui.devops.web.service.SSHService;
import com.youaishujuhui.devops.web.service.host.HostService;
import com.youaishujuhui.devops.web.vo.Result;

import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;

@Controller
@RequestMapping("/log")
public class LogController {
	
    @Autowired
    private SSHService sshService;
    
    @Autowired
	private HostService hostService;
    
    private static final int FETCH_LINE = 20;
    
    @RequestMapping("/getSelf")
    @ResponseBody
    public Result<LogResultPO> getSelf(String logFilePath, Integer curLine){
        Result<LogResultPO> result = new Result<>();
        LogResultPO po = new LogResultPO();
        result.setData(po);

	    String cmd = String.format("wc -l %s|awk '{print $1}'", logFilePath);
	    String execResult;
	    
	    int totalLine = 0;
		try {
			execResult = RuntimeUtil.execForStr("sh", "-c", cmd);
			totalLine = Integer.parseInt(execResult.trim());
			
			if (curLine == -1) {
				// 第一次请求，从文件末尾开始输出
				curLine = totalLine;

		    	// 如果大于20行，从当前行的上面20行开始输出，为了用户体验，你懂得
		    	if (curLine > FETCH_LINE) {
		    		curLine -= FETCH_LINE;
		    	}
			}
			
			if (curLine > totalLine + 1) {
				// 执行到这里表示日志出现了轮转，从头输出
				curLine = 1;
			}
			
			cmd = String.format("sed -n %d,%dp %s", curLine, curLine + FETCH_LINE, logFilePath);
			execResult = RuntimeUtil.execForStr("sh", "-c", cmd);
			String log = execResult.trim().replaceAll("\\n", "<br>");
			
			int lineCount = StrUtil.count(log, "<br>");
			
			if (!StrUtil.isBlank(log)) {
				// 输出有几行
				log = log.replaceAll("\\n", "<br>")
						.replaceAll("\\e\\[1;32m", "<font color=\"green\">")
						.replaceAll("\\e\\[0m", "</font>")
						.replaceAll("\\e\\[1;31m", "<font color=\"red\">");
				po.setLog(log);
				po.setNextLine(curLine + lineCount + 1);
			} else {
				po.setNextLine(curLine + lineCount);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

        return result;
    }

    @RequestMapping("/get")
    @ResponseBody
    public Result<LogResultPO> get(String logFilePath, Integer hostId, Integer curLine){
        Result<LogResultPO> result = new Result<>();
        LogResultPO po = new LogResultPO();
        result.setData(po);
        
        Host host = hostService.fetch(hostId);
        
        if (host == null) {
        	result.setCode(Result.FAIL);
        	result.setMsg("主机不存在");
        	return result;
        }
        
	    String cmd = String.format("wc -l %s|awk '{print $1}'", logFilePath);
	    
	    SSHExecResult execResult;
	    int totalLine = 0;
		try {
			execResult = sshService.execUseCache(host.getAvailablePublicIp(), host.getSshPort(), cmd);
			totalLine = Integer.parseInt(execResult.getStdout().trim());

			if (curLine == -1) {
				// 第一次请求，从文件末尾开始输出
				curLine = totalLine;

		    	// 如果大于20行，从当前行的上面20行开始输出，为了用户体验，你懂得
		    	if (curLine > FETCH_LINE) {
		    		curLine -= FETCH_LINE;
		    	}
			}
			
			if (curLine > totalLine + 1) {
				// 执行到这里表示日志出现了轮转，从头输出
				curLine = 1;
			}
			
			cmd = String.format("sed -n %d,%dp %s", curLine, curLine + FETCH_LINE, logFilePath);
			execResult = sshService.execUseCache(host.getAvailablePublicIp(),host.getSshPort(), cmd);
			if (execResult.getExitStatus() == 0 &&
					StringUtils.isEmpty(execResult.getStderr())) {
		    	
				String log = execResult.getStdout().trim().replaceAll("\\n", "<br>");
				
				int lineCount = StrUtil.count(log, "<br>");
				//System.out.println(lineCount);
				//System.out.println(log);
				
				if (!StrUtil.isBlank(log)) {
					// 输出有几行
					po.setLog(log);
					po.setNextLine(curLine + lineCount + 1);
				} else {
					po.setNextLine(curLine + lineCount);
				}
		    }
		} catch (Exception e) {
			e.printStackTrace();
		}

        return result;
    }

}
